<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        li {
            list-style: none;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        img {
            vertical-align: top;
        }

        .main {
            width: 1226px;
            margin: 0 auto;
            margin-top: 50px;
        }

        .grade-list {
            margin-top: 20px;
        }

        .grade-list table {
            width: 100%;
            border-collapse: collapse;
            text-align: center;
            font-size: 13px;
            line-height: 40px;
            table-layout: fixed;
        }

        .grade-list table td,
        .grade-list table th {
            border: 1px solid #666;
        }

        /* 遮罩层 */
        .shadow {
            width: 100%;
            height: 100%;
            position: fixed;
            left: 0;
            top: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
            display: none;
        }

        .shadow .edit-box {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #fff;
            font-size: 13px;
        }

        .shadow .edit-box .input-group+.input-group {
            margin-top: 10px;
        }

        .shadow .edit-box .input-group input[type='text'] {
            width: 250px;
            height: 30px;
            vertical-align: middle;
            border: 1px solid #000;
            border-radius: 2px;
            outline: none;
            font-size: 13px;
            margin-left: 5px;
            text-indent: 5px;
        }

        .shadow .edit-box .input-group input:disabled {
            border: 0;
            /* color: gray; */
            background-color: transparent;
        }

        /* 搜索 */
        /* 搜索 */

        .searchGrade {
            display: flex;
            margin-bottom: 10px;
            /* justify-content: space-between; */
        }

        .searchGrade>* {
            margin-right: 20px;
            line-height: 30px;
        }

        .searchGrade .searchBar {
            width: 300px;
            height: 29px;
            border: 1px solid #333;
            display: flex;
            overflow: hidden;
        }

        .searchGrade .searchBar .searchCon {
            border: none;
            outline: none;
            flex: 1;
            padding: 0;
            text-indent: 5px;
        }

        .searchGrade .searchBar .searchBtn {
            width: 60px;
            height: 30px;
            display: block;
            background-color: #999;
        }

        .searchGrade .orderColBar,
        .searchGrade .orderTypeBar {
            border: 1px dashed #999;
            padding: 0 20px;
        }

        .searchGrade label {
            margin-right: 10px;
        }

        .searchGrade select {
            height: 30px;
        }

        .searchGrade input[type="reset"] {
            height: 30px;
            width: 45px;
        }

        .pageBox {
            text-align: center;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div class="main">
        <form class="searchGrade" onsubmit="return false">
            <div class="searchBar">
                <input type="text" class="searchCon">
                <a href="javascript:;" class="searchBtn"></a>
            </div>
            <div class="orderColBar">
                <!-- 排序的列名 -->
                <label>默认<input type="radio" name="col" class="orderCol" value="id" checked></label>
                <label>语文<input type="radio" name="col" class="orderCol" value="chinese"></label>
                <label>数学<input type="radio" name="col" class="orderCol" value="math"></label>
                <label>英语<input type="radio" name="col" class="orderCol" value="english"></label>
                <label>总分<input type="radio" name="col" class="orderCol" value="total"></label>
            </div>
            <div class="orderTypeBar">
                <!-- 排序的方式 -->
                <label>升序<input type="radio" name="type" class="orderType" value="asc" checked></label>
                <label>降序<input type="radio" name="type" class="orderType" value="desc"></label>
            </div>
            <div class="showNumSelect">
                <select class="showNum">
                    <option value="5" selected>每页显示5条</option>
                    <option value="10">每页显示10条</option>
                    <option value="15">每页显示15条</option>
                    <option value="20">每页显示20条</option>
                </select>
            </div>
            <input type="reset" value="重置">
        </form>
        <div class="grade-list">
            <table class="garde-table">
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>姓名</th>
                        <th>班级</th>
                        <th>语文</th>
                        <th>数学</th>
                        <th>英语</th>
                        <th>总分</th>
                        <th>编辑</th>
                        <th>删除</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-id="49">
                        <td>49</td>
                        <td>小王</td>
                        <td>2101</td>
                        <td>0</td>
                        <td>0</td>
                        <td>0</td>
                        <td>0</td>
                        <td><a href="javascript:;" class="edit">编辑</a></td>
                        <td><a href="javascript:;" class="delete">删除</a></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="pageBox">
            <button class="prev">上一页</button>
            <span class="page-tips">1/46</span>
            <button class="next">下一页</button>

        </div>
    </div>
    <div class="shadow">
        <form class="edit-box" onsubmit="return false">
            <div class="input-group">
                <label>编号:<input type="text" disabled name="id"></label>
            </div>
            <div class="input-group">
                <label>姓名:<input type="text" disabled name="name"></label>
            </div>
            <div class="input-group">
                <label>班级:<input type="text" disabled name="class"></label>
            </div>
            <div class="input-group">
                <label>语文:<input type="text" name="chinese"></label>
            </div>
            <div class="input-group">
                <label>数学:<input type="text" name="math"></label>
            </div>
            <div class="input-group">
                <label>英语:<input type="text" name="english"></label>
            </div>
            <div class="input-group">
                <button class="save">保存</button>
                <input type="reset" class="cancel" value="取消">
            </div>
        </form>
    </div>

</body>
<script type="module">
    import { ajax } from "../js/ajax.js"

    var gardeTable = document.getElementsByClassName("garde-table")[0];
    var tbody = document.querySelector(".grade-list tbody");
    var shadow = document.querySelector(".shadow");

    var searchGrade = document.querySelector(".searchGrade");
    var showNum = document.querySelector(".showNum");


    var idInput = document.getElementsByName("id")[0];
    var nameInput = document.getElementsByName("name")[0];
    var classInput = document.getElementsByName("class")[0];
    var chineseInput = document.getElementsByName("chinese")[0];
    var mathInput = document.getElementsByName("math")[0];
    var englishInput = document.getElementsByName("english")[0];

    var save = document.getElementsByClassName("save")[0];
    var cancel = document.getElementsByClassName("cancel")[0];

    var prev = document.getElementsByClassName("prev")[0];
    var next = document.getElementsByClassName("next")[0];
    var pageTips = document.getElementsByClassName("page-tips")[0];


    // 全局变量 => 存储搜索 排序 分页 => 数据
    var wd = "";  // "" 默认查询所有数据  
    var col = "id"; //数据默认按编号排序
    var type = "asc"; //排序的方式
    var page = 1;   // 默认显示第一页
    var size = 5;   // 每页显示五条


    // http://121.43.116.41/demo/php/searchAllGrade.php

    // 页面加载时请求所有数据
    loadGrade();

    // 事件委托 => 绑定删除和编辑事件
    searchGrade.addEventListener("click", searchHandler)
    showNum.addEventListener("change", function () {
        size = this.value;
        loadGrade();
    })

    gardeTable.addEventListener("click", gradeHandler);
    save.addEventListener("click", saveHandler);
    cancel.addEventListener("click", cancelHandler);




    function loadGrade() {
        // var xhr = new XMLHttpRequest();

        // xhr.open("get", "http://121.43.116.41/demo/php/searchAllGrade.php", true)

        // xhr.send();

        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState == 4 && xhr.status == 200) {
        //         var res = xhr.responseText;
        //         console.log(res);  // json字符串
        //         res = JSON.parse(res);
        //         console.log(res);  // js对象


        //         }

        //     }
        // }

        ajax({
            type: "get",
            url: "http://121.43.116.41/demo/php/searchGradeOrderLimit.php",
            data: {
                wd: wd,
                col,
                type,
                page,
                size
            },
            dataType: "json",
            success: function (res) {
                console.log("grade载入完毕", res);
                var { status, message, list, current, maxPage, total } = res;
                
                //  问题: 页面多的(显示少) 向页码少(多)的切换时  => 可以页码(page)会超出页面少的页面的临界值
                //  数据: 83
                //  每页显示5条 =>  17页
                //  每页显示10条 =>  9页

                // 假如 每页显示5条时,正处于17页(page=17)  => 切换到每页显示10条  => page就会超出

                // 如何解决？
                // 如何page超出masPage(最大页) => page赋值为最大页
                console.log(page = page > maxPage ? maxPage : page);
                page = page > maxPage ? maxPage : page;


                pageTips.textContent = `${current}/${maxPage}`;



                prev.onclick = function () {
                    if (page <= 1) return false;
                    page--;
                    loadGrade();
                }

                next.onclick = function () {
                    if (page >= maxPage) return false;
                    page++;
                    loadGrade();
                }

                if (status) {  // 可以使用的邮箱
                    var html = "";
                    list.forEach((item) => {
                        var { id, name, class: cls, chinese, math, english, total } = item;
                        html += `<tr data-id="${id}">
                            <td>${id}</td>
                            <td>${name}</td>
                            <td>${cls}</td>
                            <td>${chinese}</td>
                            <td>${math}</td>
                            <td>${english}</td>
                            <td>${total}</td>
                            <td><a href="javascript:;" class="edit">编辑</a></td>
                            <td><a href="javascript:;" class="delete">删除</a></td>
                        </tr>`;
                    })
                    tbody.innerHTML = html;
                }
            }
        })
    }

    function searchHandler(e) {
        var e = e || window.event;
        var target = e.target;

        if (target.className == "searchBtn") {
            console.log("点击搜索按钮");
            var searchCon = target.previousElementSibling;
            wd = searchCon.value.trim();
            loadGrade();


        } else if (target.className == "orderCol") {
            console.log("按列名排序");
            col = target.value;
            loadGrade();

        } else if (target.className == "orderType") {
            console.log("按列名方式");
            type = target.value;
            loadGrade();

        } else if (target.type == "reset") {
            console.log("点击重置");

            wd = "";  // "" 默认查询所有数据  
            col = "id"; //数据默认按编号排序
            type = "asc"; //排序的方式
            page = 1;   // 默认显示第一页
            size = 5;   // 每页显示五条

            loadGrade();
        }
    }

    function gradeHandler(e) {
        var e = e || window.event;
        var target = e.target;

        if (target.className == "delete") {
            deleteHandler.call(target);
        } else if (target.className == "edit") {
            editHandler.call(target);
        }
    }

    function deleteHandler() {
        if (confirm("是否删除该商品?")) {
            var parentEle = this.parentElement.parentElement;

            var id = parentEle.dataset.id;
            console.log(id);


            // 页面加载时请求所有数据
            var xhr = new XMLHttpRequest();

            xhr.open("get", "http://121.43.116.41/demo/php/deleteGradeById.php?id=" + id, true)

            xhr.send();

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var res = xhr.responseText;
                    // console.log(res);  // json字符串
                    res = JSON.parse(res);
                    console.log(res);  // js对象

                    var { status, message, list } = res;
                    if (status) {  // 可以使用的邮箱
                        parentEle.remove();
                    }

                }
            }

        }
    }

    function editHandler() {
        var parentEle = this.parentElement.parentElement;
        var id = parentEle.dataset.id;
        console.log(id);

        // 页面加载时请求所有数据
        var xhr = new XMLHttpRequest();

        xhr.open("get", "http://121.43.116.41/demo/php/searchGradeById.php?id=" + id, true)

        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var res = xhr.responseText;
                // console.log(res);  // json字符串
                res = JSON.parse(res);
                console.log(res);  // js对象

                var { status, message, data } = res;

                shadow.style.display = "block";

                // if (status) {  // 可以使用的邮箱
                //     parentEle.remove();
                // }

                idInput.value = data.id;
                nameInput.value = data.name;
                classInput.value = data.class;
                chineseInput.value = data.chinese;
                mathInput.value = data.math;
                englishInput.value = data.english;

            }
        }

    }

    function saveHandler() {
        var id = idInput.value;
        var ch = chineseInput.value * 1;
        var mh = mathInput.value * 1;
        var eh = englishInput.value * 1;


        // 写一个正则验证分数 0-100的分数 
        // 可以传整数 
        // 也可以传小数  0.x

        // 整数部分
        // 0-9    \d
        // 10-99  [1-9]\d
        // 100 
        // 小数部分
        // (\.\d)?

        var sorce = /^((\d|[1-9]\d)(\.\d)?|100(\.0)?)$/;

        // console.log(sorce.test(ch));
        if (!sorce.test(ch)) {
            alert("语文分数有误")
        } else if (!sorce.test(mh)) {
            alert("数学分数有误")
        } else if (!sorce.test(eh)) {
            alert("英语分数有误")
        } else {
            var xhr = new XMLHttpRequest();

            xhr.open("post", "http://121.43.116.41/demo/php/updateGradeById.php", true);

            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(`id=${id}&ch=${ch}&eh=${eh}&mh=${mh}`);


            // 如果该请求已被发出，XMLHttpRequest.abort() 方法将终止该请求。当一个请求被终止，它的 readyState 将被置为 XMLHttpRequest.UNSENT (0)，并且请求的 status 置为 0。

            xhr.onload = function () {
                var res = xhr.responseText;
                // console.log(res);
                res = JSON.parse(res);
                console.log(res);

                var { status, message } = res;
                if (status) {
                    shadow.style.display = "none";
                    // location.reload();

                    loadGrade();
                } else {
                    alert(message);
                }







            }
        }


    }

    function cancelHandler() {
        shadow.style.display = "none";
    }
</script>

</html>